package com.jxb.three;

import java.util.ArrayList;
import java.util.List;

/**
 * 螺旋矩阵
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 *
 * 1 2 3
 * 4 5 6
 * 7 8 9
 *
 *
 *
 */
public class SpiralMatrix_54 {

    public static void main(String[] args) {
//        int count = (Math.min(3,3) + 1)/2;
//        System.out.println(count);
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        List<Integer> integers = spiralOrder(matrix);
        System.out.println("---");
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0) {
            return list;
        }

        int rowLength = matrix.length;
        int colLength = matrix[0].length;
        //层数指示器
        int plies = 0;
        //矩阵的层数
        int count = (Math.min(rowLength,colLength) + 1)/2;
        //从外部向内部遍历，逐层打印数据
        // * 1 2 3
        // * 4 5 6
        // * 7 8 9
        //plies = 0：
            //从左至右：1,2,3
            //从上至下：6,9
            //从右至左：8,7
            //从下至上：4
        while (plies < count) {
            //每层矩阵的起始元素matrix[plies][plies]
            /*从左至右，到matrix[plies][colLength-1-plies]时停止，准备转向*/
            //plies:0,j:0,1,2
            //4
            for (int j = plies; j < colLength - plies;j++) {
                list.add(matrix[plies][j]);
            }
            //从上往下进行处理
            //plies:0,j:1,2
            for (int j = plies+1; j<rowLength - plies;j++) {
                list.add(matrix[j][(colLength-1)-plies]);
            }
            //从右往左进行遍历
            //plies:0,j:0
            //8(2,1),7(2,0)
            for (int j = (colLength-1)-(plies+1);j >= plies && (rowLength - 1 - plies != plies);j--) {
                list.add(matrix[(rowLength-1)-plies][j]);
            }
            //从下往上进行遍历
            //plies:0,j:1,2
            //4(1,0)
            for (int j = (rowLength-1)-(plies+1); j >= plies + 1 && (colLength-1-plies != plies);j--) {
                list.add(matrix[j][plies]);
            }
            //层数累加
            plies++;
        }
        return list;
    }



}
